<?php

/**
 * Storage server public interface. 
 * Need the ZendFramework initialized, specially the class Zend_Loader and an include_path pointing to  dirname(__FILE__) . '../..'
 * 
 */
class Ext_Storage_Client
{

    /**
     * Default constructor.
     * If serverUrl is null then the server is local and I simply do a function call.
     *
     */
    public function __construct( $serverUrl = null )
    {
        if ( $serverUrl === null ) {
            // bootstrap (localy) the server.
            if ( ! class_exists( 'Storage_StorageServer' ) ) {
                return new Ext_Error( 'You must include the file storage_service.php or give the service url' );
            }
            $this->storageServer = new Storage_StorageServer( );
        } else {
            $this->storageServer = new SoapClient( $serverUrl, array( 
                            'exceptions' => true, 
                            'trace' => 1 
            ) );
            if ( ! isset( $this->storageServer ) ) {
                return new Ext_Error( 'Error creating the SoapClient' );
            }
        }
        return null;
    }

    /**
     * Implements the call to the server of interface Ext_Storage_Interface
     */
    public function __call( $name, $arguments )
    {
        if ( in_array( $name, get_class_methods( 'Ext_Storage_Interface' ) ) ) {
            $ret = new Ext_Error( 'Soap client error' );
            try {
                $ret = call_user_func_array( array( 
                                $this->storageServer, 
                                $name 
                ), $arguments );
            } catch( Exception $e ) {
                if ( $this->storageServer instanceof SoapClient ) {
                    return new Ext_Error( "Soap client error : " . $e->getMessage() . "\n" . $this->storageServer->__getLastResponse() . "\n" . $e->getTraceAsString() );
                } else {
                    return new Ext_Error( "Soap client error : " . $e->getMessage() . "\n" . $e->getTraceAsString() );
                }
            }
            return $ret;
        }
        return new Ext_Error( 'Invalid Method' );
    }
}
